#!/bin/bash
set -ex  

if [ -z "$1" ]; then
    LAST_TAG=$(git tag | grep -v "^v" | tail -n 1)
    if [ -z "$LAST_TAG" ]; then
        VER="0.0.1"
        echo "未找到历史标签，初始版本号：$VER"
    else
        VER=$(echo "$LAST_TAG" | python3 -c "
import sys
vers = sys.stdin.readline().strip().split('.')
if len(vers) != 3:
    sys.exit('标签格式错误，需为 x.y.z（如 0.0.1）')
try:
    vers[2] = str(int(vers[2]) + 1)
    print('.'.join(vers))
except ValueError:
    sys.exit('标签补丁版本不是数字')
")
    fi
else
    VER="$1"  
fi

if git rev-parse "$VER" >/dev/null 2>&1; then
    echo "错误：标签 $VER 已存在！请更换版本号或删除现有标签（git tag -d $VER && git push origin :refs/tags/$VER）"
    exit 1
fi

git tag -a "$VER" -m "Release version $VER"
git push -u origin "$VER"

docker build -t "crpi-sq7938wquqynh0xp.cn-guangzhou.personal.cr.aliyuncs.com/kim218/demo_fe:$VER" .

docker push "crpi-sq7938wquqynh0xp.cn-guangzhou.personal.cr.aliyuncs.com/kim218/demo_fe:$VER"

echo "构建推送完成！镜像地址："
echo "crpi-sq7938wquqynh0xp.cn-guangzhou.personal.cr.aliyuncs.com/kim218/demo_fe:$VER"
